import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { Button, Checkbox, Form, Input, message, Modal, Select, Spin, Tooltip } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';
import { uniqBy } from 'lodash';
import { AntdBaseTable } from '@/base/TBaseTable';
import { HttpCode } from '#/utils/contacts.js';
import TRNotification from '#/utils/notification.js';
import { TRDefault } from '@/components/index.js';
import planIcon from '@/assets/img/plan_icon.png';
import type { INoticeSequenceListType, ISearchFormData } from '../../type';
import { getTodoNoticeSequenceListH, relationPending, relationPendingH } from '../../service';
import { RadioSwitch, ShowDatePicker } from '../index';
import { CONNECT_TYPE, TODO_STATUS, TYPE_LIST_ARR } from '../../dictionary';
// import { uniqueFunc } from '../../tool';
import styles from './index.less';

interface IProps {
  /**
   * 关联代办的id
   */
  id: number;
  /**
   * 已关联的公告或序列
   */
  value: string[];
  /**
   * 已关联公告/序列
   */
  data: INoticeSequenceListType[];
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 刷新key值
   */
  setFlashKey: (e: number) => void;
  onPress: (data: Record<string, any>) => void;
}

const { Option } = Select;

const ConnectNSModalComponent = (props: IProps) => {
  const [form] = Form.useForm();
  const { id, searchFormData, value, data, onPress, setFlashKey, marketId } = props;
  const { marketOptions } = searchFormData;
  const markets = marketOptions.map((item) => item.value).join(',');
  const initialValues = {
    queryType: 'GG_XL',
    marketList: markets,
    keyWords: '',
    date: [
      moment().endOf('month').diff(moment(), 'day') ? moment().add(1, 'day') : moment(),
      moment().endOf('month'),
    ],
  };

  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [checked, setChecked] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<INoticeSequenceListType[]>([]);
  const [allData, setAllData] = useState<INoticeSequenceListType[]>(data);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [selectedRowData, setSelectedRowData] = useState<INoticeSequenceListType[]>(data);

  // 搜索列表数据
  const onSearch = async (params: any) => {
    setLoading(true);

    const res = await getTodoNoticeSequenceListH(params).catch(() => null);

    // 如果res存在且状态码为SUCCESS
    if (res?.statusCode === HttpCode.SUCCESS) {
      const _data = uniqBy(res.data || [], 'id');
      setDataSource([..._data]);
      setAllData([..._data]);
    }
    setLoading(false);
  };

  useEffect(() => {
    const { marketList, date, ...rest } = initialValues;
    const params = {
      marketList: marketList.split(','),
      startDate: moment(date[0]).format('YYYY-MM-DD'),
      endDate: moment(date[1]).format('YYYY-MM-DD'),
      ...rest,
    };
    onSearch(params);
  }, []);

  useEffect(() => {
    if (value.length > 0) {
      const list = Array.from(new Set([...selectedRowKeys, ...value]));
      setSelectedRowKeys(list);
    }
  }, [value]);

  // useEffect(() => {
  //   if(value.length > 0){
  //     const list = uniqueFunc([...selectedRowData, ...data], 'id');
  //     setSelectedRowData(list);
  //     const all = uniqueFunc([...allData, ...data], 'id');
  //     setAllData(all);
  //   }
  // }, [data]);

  // 确定按钮
  const _onOk = async () => {
    setBtnLoading(true);
    const params = {
      id,
      relaInfo: selectedRowData.map((item: INoticeSequenceListType) => {
        return {
          type: item.type,
          noticeAttachId: item.id,
        };
      }),
    };
    let res: any = {};
    if (marketId === 'PDBLJ') {
      res = await relationPendingH(params);
    } else {
      res = await relationPending(params);
    }

    if (res && res.statusCode === HttpCode.SUCCESS) {
      message.info('关联成功！');
      onPress({ index: 1 });
      setVisible(false);
      setFlashKey(moment().valueOf());
    } else {
      message.info(res?.message || '关联失败！');
    }
    setBtnLoading(false);
  };

  // 取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 查看关联数据
  const onChangeConnected = (e: boolean) => {
    if (e) {
      setLoading(false);
      setDataSource(data);
    } else {
      const _value = form && form.getFieldsValue();
      const { marketList, date, ...rest } = _value || {};
      const params = {
        marketList: marketList.split(','),
        startDate: moment(date[0]).format('YYYY-MM-DD'),
        endDate: moment(date[1]).format('YYYY-MM-DD'),
        ...rest,
      };
      onSearch(params);
    }
    setChecked(e);
  };

  // 点击查询
  const onFinish = () => {
    form &&
      form.validateFields().then((val) => {
        const { marketList, date, ...rest } = val;
        const params = {
          marketList: marketList.split(','),
          startDate: moment(date[0]).format('YYYY-MM-DD'),
          endDate: moment(date[1]).format('YYYY-MM-DD'),
          ...rest,
        };
        onSearch(params);
      });
    setChecked(false);
  };

  // 选择列表数据
  const onSelectRows = (a: string[]) => {
    const rowData = allData.filter((x) => a.includes(x.id));
    setSelectedRowData(rowData);
    setSelectedRowKeys(a);
  };
  const noticeAndSequenceColumns = [
    {
      code: 'date',
      name: '日期',
      width: 80,
      render(v: string) {
        return v ? moment(v).format('YYYYMMDD') : '-';
      },
    },
    {
      code: 'marketName',
      name: '交易中心',
      width: 140,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'type',
      name: '类型',
      width: 100,
      render(v: string) {
        const _data = TYPE_LIST_ARR.find((item) => item.value === v);
        return _data?.label || '-';
      },
    },
    {
      code: 'content',
      name: '内容',
      width: 280,
      render(v: string) {
        return (
          <Tooltip placement="topLeft" title={v} overlayClassName={styles.tooltip}>
            <div className={styles.online}>{v || '-'}</div>
          </Tooltip>
        );
      },
    },
    {
      code: 'declarationStartTime',
      name: '交易时间',
      width: 80,
      render(v: string, record: INoticeSequenceListType) {
        const _data =
          record.declarationStartTime && record.declarationEndTime
            ? `${moment(record.declarationStartTime).format('HHmm')}-${moment(
                record.declarationEndTime,
              ).format('HHmm')}`
            : '-';
        return _data;
      },
    },
    {
      code: 'executionStartDate',
      name: '执行起止时间',
      width: 160,
      render(v: string, record: INoticeSequenceListType) {
        const _data =
          record.executionStartDate && record.executionEndDate
            ? `${moment(record.executionStartDate).format('YYYYMMDD')}-${moment(
                record.executionEndDate,
              ).format('YYYYMMDD')}`
            : '-';
        return _data;
      },
    },
    {
      code: 'createUserName',
      name: '创建人',
      width: 80,
      render(v: string) {
        return v || '-';
      },
    },
    {},
  ];

  // 提交关联列表
  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={btnLoading}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={_onOk} loading={btnLoading}>
      关联
    </Button>,
  ];

  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({ dataSource, columns: noticeAndSequenceColumns })
    .primaryKey('id') // 每一行数据由 id 字段唯一标记
    .use(
      features.multiSelect({
        value: selectedRowKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: (a) => {
          onSelectRows(a);
        },
      }),
    )
    .appendRowPropsGetter((_row): any => {
      const color = _row.status === TODO_STATUS.OVERDUE_TYPE ? '#383C3E' : '#222629';
      return {
        style: { '--bgcolor': color },
      };
    });

  return (
    <Modal
      width="60%"
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}> 关联公告/序列 </span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <div className={styles.search}>
          <Form form={form} name="connect" initialValues={initialValues} className={styles.form}>
            <Form.Item name="queryType">
              <Select className={styles.select} options={CONNECT_TYPE} />
            </Form.Item>
            <Form.Item name="marketList">
              <Select className={styles.marketList}>
                <Option value={markets}>全部</Option>
                {marketOptions.map((item) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="keyWords">
              <Input placeholder="请输入关键字" autoComplete="off" allowClear />
            </Form.Item>
            <Form.Item name="date">
              <ShowDatePicker
                type={'rangePicker'}
                format="YYYYMMDD"
                placeholder={['开始时间', '结束时间']}
              />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className={styles.searchBtn}
                loading={loading}
                onClick={onFinish}
              >
                查询
              </Button>
            </Form.Item>
          </Form>
          <RadioSwitch value={checked} onChange={onChangeConnected} text="查看已选择" />
        </div>
        <div className={styles.antdBaseTable}>
          <Spin spinning={loading}>
            {loading ? null : !dataSource.length ? (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            ) : (
              <AntdBaseTable
                useVirtual={true}
                style={{
                  '--row-height': '28px',
                  // '--header-bgcolor': '#383C3E',
                  '--header-row-height': '28px',
                  '--cell-padding': '4px',
                  // '--cell-border-vertical': '1px solid #4F4F4F',
                  // '--header-cell-border-vertical': '1px solid #4F4F4F',
                  // '--highlight-bgcolor': '#21323E',
                  borderRadius: '5px',
                  border: '1px solid var(--bd)',
                  width: '100%',
                  height: '100%',
                  overflow: 'auto',
                }}
                {...pipeline.getProps()}
              />
            )}
          </Spin>
        </div>
      </div>
    </Modal>
  );
};

class ConnectNSModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ConnectNSModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ConnectNSModal();
